package com.leetcode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 447. 回旋镖的数量
 *
 * @author fy
 * @date 2022/4/8 18:44
 */
public class Solution447 {

    public int numberOfBoomerangs(int[][] points) {
        if (points == null || points.length < 3) {
            return 0;
        }

        int res = 0;
        for (int i = 0; i < points.length; i++) {
            int[] p = points[i];
            // 将距离相等的点做映射
            Map<Integer, Integer> map = new HashMap<>(points.length);
            for (int j = 0; j < points.length; j++) {
                if (i != j) {
                    int[] q = points[j];
                    int dist = (p[0] - q[0]) * (p[0] - q[0]) + (p[1] - q[1]) * (p[1] - q[1]);
                    map.put(dist, map.getOrDefault(dist, 0) + 1);
                }
            }
            for (Integer dist : map.keySet()) {
                int count = map.get(dist);
                if (count > 1) {
                    res += count * (count - 1);
                }
            }
        }

        return res;
    }

    /**
     * 简化版本
     *
     * @param points
     * @return
     */
    public int numberOfBoomerangs1(int[][] points) {
        if (points == null || points.length < 3) {
            return 0;
        }

        int res = 0;
        for (int[] p : points) {
            // 将距离相等的点做映射
            Map<Integer, Integer> map = new HashMap<>(points.length);
            for (int[] q : points) {
                int dist = (p[0] - q[0]) * (p[0] - q[0]) + (p[1] - q[1]) * (p[1] - q[1]);
                map.put(dist, map.getOrDefault(dist, 0) + 1);
            }
            for (Integer dist : map.keySet()) {
                int count = map.get(dist);
                res += count * (count - 1);
            }
        }

        return res;
    }

}
